package com.lzq.mq.nameserver.core;

import com.lzq.mq.nameserver.common.CommonCache;
import com.lzq.mq.nameserver.store.ServiceInstance;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.lzq.mq.common.constants.NameServerConstants.*;

/**
 * 服务下线任务
 * 将超时未收到心跳的服务实例下线
 */
@Slf4j
public class InValidServiceRemoveTask implements Runnable {
    @Override
    public void run() {
        log.info("服务超时检查任务启动");
        while (true) {

            try {
                TimeUnit.SECONDS.sleep(HEART_BEAT_TIMEOUT_SCANNER_RATE_S);
            } catch (InterruptedException e) {
                log.error("服务下线任务异常", e);
                throw new RuntimeException(e);
            }

            Map<String, ServiceInstance> serviceInstanceMap = CommonCache.getServiceInstanceManager().getServiceInstanceMap();
            Iterator<String> iterator = serviceInstanceMap.keySet().iterator();     // 使用迭代器更加安全

            long currentTimestamp = System.currentTimeMillis();
            /*
                在循环中删除元素不安全！！！
             */
            while (iterator.hasNext()) {
                String address = iterator.next();
                ServiceInstance serviceInstance = serviceInstanceMap.get(address);
                if (serviceInstance.getLastHeartBeatTime() == null) {
                    log.warn("服务实例没有心跳时间:{}", address);
                    continue;
                }
                if (currentTimestamp - serviceInstance.getLastHeartBeatTime() > SERVER_HEART_BEAT_TIMEOUT_MS) {
                    log.info("服务实例已超时:{}", address);
                    iterator.remove();      // 迭代器删除更加安全
                }
            }
        }

    }
}
